package cn.bugio.note.service.user.impl;

import cn.bugio.note.common.domain.dto.UserDTO;
import cn.bugio.note.common.vo.ServerResponse;
import cn.bugio.note.dao.user.UserMapper;
import cn.bugio.note.domain.dto.user.UserLoginReqDTO;
import cn.bugio.note.domain.entity.user.User;
import cn.bugio.note.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author Vincent Vic
 * @version 1.0
 * @Description
 * @since 2021/2/16
 */

@Service("userService")
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;

    /**
     * 通过id查找用户
     *
     * @param id
     * @return
     */
    @Override
    public ServerResponse<UserDTO> findById(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null){
            return ServerResponse.error(404,"找不到用户");
        }
        BeanCopier beanCopier = BeanCopier.create(User.class, UserDTO.class, false);
        UserDTO userDTO = new UserDTO();
        beanCopier.copy(user,userDTO,null);
        return ServerResponse.success(userDTO);
    }

    /**
     * 登入
     *
     * @param loginReqDTO
     * @param openId
     * @return
     */
    @Override
    public ServerResponse<User> login(UserLoginReqDTO loginReqDTO, String openId) {
        User user = userMapper.selectOne(
          User.builder()
                .wxId(openId)
                .build()
        );

        if (user == null) {
            userMapper.insertSelective(
                    User.builder()
                        .wxId(openId)
                        .avatarUrl(loginReqDTO.getAvatarUrl())
                        .wxNickname(loginReqDTO.getWxNickname())
                        .roles("user")
                        .createTime(new Date())
                        .bonus(100)
                        .build()
            );
        }

        return ServerResponse.success(user);
    }
}
